<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<!--标准mui.css-->
		<link href="../css/app.css" rel="stylesheet" />
		<link href="../cssmui/mui.min.css" rel="stylesheet">
		<script type="text/javascript" src="../mui/mui.min.js"></script>
		<script src='../js/template-web.js'></script>
		<script type="text/javascript" src="../js/app.js"></script>
		<script type="text/javascript" src="../db/design.js"></script>
		<script type="text/javascript" src="../db/dbtools.js"></script>
		<script type="text/javascript" src="../db/dbmanager.js"></script>
		<script type="text/javascript" src="../js/zdyfile.js"></script>
		<script src="../js/map/serverurls.js"></script>
		<script src="../mui/common.js"></script>
		<script src="../js/jsondb.js"></script>
		<style type="text/css">
			.mui-content {
				margin-bottom: 70px;
			}
		</style>
	</head>

	<body>
		<header class="mui-bar mui-bar-nav">
			<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
			<h1 class="mui-title">数据云盘</h1>
		</header>
		<div class="mui-content">
			<div></div>
			<ul class="ulist mui-table-view ">
			</ul>
		</div>
		<nav class="mui-bar mui-bar-tab">
			<a class="btbackupdb mui-tab-item">
				<span class="mui-tab-label">备份数据</span>
			</a>
			<a class="btbacklist mui-tab-item">
				<span class="mui-tab-label">数据列表</span>
			</a>
			<a class="btbackupimg mui-tab-item">
				<span class="mui-tab-label">备份图片</span>
			</a>
			<a class="btimglist mui-tab-item">
				<span class="mui-tab-label">图片列表</span>
			</a>
		</nav>

		<script id="node_tpl" type="text/html">
			<li class="mui-table-view-cell mui-media">
				<span class="mui-ellipsis" style="color:#777777; ">文件：{{srcfile}}</span>
				<a class="mui-pull-right mui-btn-grey btrestore" tagfile="{{tagfile}}" srcfile="{{srcfile}}">
					还原
				</a>
			</li>
		</script>
		<script id="img_tpl" type="text/html">
			<li class="mui-media" style="margin-left:10px;margin-right:5px;padding-top:9px">
				<img id="{{srcfile}}" class="mui-pull-left " src="{{path+srcfile}}" width="90px" height="90px">
				<span class="mui-media-body" style="margin-top:20px;margin-right:20px;">
					 <p class='mui-ellipsis-2'>{{srcfile}}</p>
					<div>
				{{fsize}} k
				<a class=" mui-btn-danger  btrestoreimg" style="margin-left:20px;"  tagfile="{{tagfile}}">
					下载
				</a>
				<a class="mui-btn-danger  btdelimg" style="margin-left:50px;" idkey="{{_idkey}}" tagfile="{{tagfile}}">
					删除
				</a>
				</div>
				</span>
			</li>
		</script>
		<script type="text/javascript">
			var DBSAVEPATH = "_documents/backup/";
			var IMGSAVEPATH = '_doc/upimgs/'; // 图片存储目录
			var REALIMGPATH = ''
			var _uuid = '123456';
			var _isload = true;

			function afterPlusReady() {
				mui.init();
				REALIMGPATH = plus.io.convertLocalFileSystemURL(IMGSAVEPATH);
				//console.log(REALIMGPATH);
				mui.ready(function() {
					mui('.mui-content').on('tap', '.btrestore', function() {
						var tagfile = this.getAttribute("tagfile");
						var srcfile = this.getAttribute("srcfile");
						restoredb(tagfile, srcfile);
					});
					mui("nav").on("tap", ".btbackupdb", function() {
						checkToken(backupdb);
					});
					mui("nav").on("tap", ".btbacklist", function() {
						checkToken(querybackdblist);
					});

					mui("nav").on("tap", ".btbackupimg", function() {
						checkToken(backupimg);
					});

					mui("nav").on("tap", ".btimglist", function() {
						checkToken(queryimglist);
					});
					mui(".mui-content").on("tap", ".btrestoreimg", function() {
						var tagfile = this.getAttribute("tagfile");
						createImgDownload(tagfile, true);
					});
					mui('.mui-content').on('tap', '.btdelimg', function() {
						var idkey = this.getAttribute("idkey");
						var tagfile = this.getAttribute("tagfile");
						delimg(idkey, tagfile);
					});
					//checkToken(querybackdblist);
				});
			}
			//

			//查询备份数据包历史目录
			function querybackdblist() {

				mui.ajax(URL_BACKDBLIST, {
					data: {
						sessionuid: _uuid
					},
					dataType: 'json', //服务器返回json格式数据
					type: 'post', //HTTP请求类型
					timeout: 10000, //超时时间设置为10秒；
					success: function(data) {
						dataToHtml(data);
					},
					error: function(xhr, type, errorThrown) {
						//异常处理；
						//for (var a in errorThrown)
						//console.log(errorThrown[a]);
					}
				});
			}

			function dataToHtml(data) {
				var table = document.body.querySelector('.ulist');
				table.innerHTML = "";
				for(var i = 0; i < data.length; i++) {
					table.innerHTML += template('node_tpl', data[i]);
				}
			}
			//还原
			function restoredb(vtagfile, vfilename) {
				checkToken(function() {
					var filepath = DBSAVEPATH + vfilename;
					plus.io.resolveLocalFileSystemURL(filepath,
						function(entry) { //文件存在，直接还原
							//	console.log("exist file"+filepath);
							setTimeout(_db.file2db(filepath), 100);
						},
						function(error) { //文件不存在，下载后还原
							console.log("no exist file=" + filepath);
							createdbDownload(vtagfile, filepath, true);
						});
				});
			}
			//备份数据库
			function backupdb() {
				_db.db2file(DBSAVEPATH, function(srcfile, tofile) {
					var path = "file://" + plus.io.convertLocalFileSystemURL(tofile);
					//console.log(path);
					createdbUpload(path);
				});

			}

			// 创建上传任务
			function createdbUpload(filepath, key) {
				var w;
				if(key) {
					w = plus.nativeUI.showWaiting("　　 开始上传...　　");
				}
				var file = _fi.analyseUrl(filepath);
				var task = plus.uploader.createUpload(URL_BACKUPLOAD, {
					method: "POST"
				}, function(upload, status) {
					if(upload.state == 4 && status == 200) {
						// 获取上传请求响应头中的Content-Type值

						var msg = JSON.parse(upload.responseText);
						if(msg.head.code == "11-0" || msg.head.code == "11-3") {
							mui.alert("身份校验异常");
						} else {
							dataToHtml(msg.body.allfiles);
							_fi.deleteDirByURL(file.path);
							// 上传完成 删除本地目录
							console.log("上传成功！" + file.path);
						}
					}
				});
				task.addData("sessionuid", _uuid);
				task.addFile(filepath, {
					key: "file"
				});
				//key=file 不能随便改，后台用来识别文件key值用，上传多个文件时key值不同
				// 设置自定义数据头
				//Content-Type:application/x-www-form-urlencoded 
				//task.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
				if(key) {
					task.addEventListener("statechanged", onUploadStateChanged, false);
				}
				task.start();
			}

			function onUploadStateChanged(upload, status) {
				if(status == 200) {
					w.close();
				}
			}
			// 创建下载任务
			function createdbDownload(vtagfile, vsrcfile, key) {
				var w;
				if(key) {
					w = plus.nativeUI.showWaiting("　　 开始下载...　　");
				}
				//console.log(vfileid);
				var options = {
					method: "POST",
					data: {
						sessionuid: _uuid,
						tagfile: vtagfile
					},
					filename: vsrcfile
				};
				dtask = plus.downloader.createDownload(URL_BACKDOWNLOAD, options,
					function(d, status) {
						if(status == 200) {
							
							mui.toast("下载成功 ！使用流量：" + (d.totalSize / 1024).toFixed(3) + 'K');
							_db.file2db(d.filename) // 安装wgt包

						} else {
							mui.toast("下载失败！");

							if(key) {
								plus.nativeUI.alert("下载更新资源失败！");
							}
						}

					});
				if(key) {
					dtask.addEventListener("statechanged", function(download, status) {
						switch(download.state) {
							case 1: // 开始
								w.setTitle("　　 开始下载...　　 ");
								break;
							case 2: // 已连接到服务器
								w.setTitle("　　 开始下载...　　 ");
								break;
							case 3:
								var a = download.downloadedSize / download.totalSize * 100;
								w.setTitle("　　 已下载" + parseInt(a) + "%　　 ");
								break;
							case 4: // 下载完成
								//console.log("download.totalSize "+download.totalSize )
								w.close();
								break;
						}
					}, false);
				}
				dtask.start();
			}
			//***********************************************
			function imgdataToHtml(data) {

				var table = document.body.querySelector('.ulist');
				table.innerHTML = "";
				if(data) {
					for(var i = 0; i < data.length; i++) {
						data[i]["path"] = REALIMGPATH;
						data[i].fsize = (data[i].fsize / 1024).toFixed(2);
						table.innerHTML += template('img_tpl', data[i]);
					}
				}
			}

			function queryimglist() {
				mui.ajax(URL_IMGLIST, {
					data: {
						sessionuid: _uuid
					},
					dataType: 'json', //服务器返回json格式数据
					type: 'post', //HTTP请求类型
					timeout: 10000, //超时时间设置为10秒；
					success: function(data) {
						imgdataToHtml(data);
					},
					error: function(xhr, type, errorThrown) {
						//异常处理；
						//for (var a in errorThrown)
						//console.log(errorThrown[a]);
					}
				});
			}

			function delimg(vidkey, vtagfile) {
				mui.ajax(URL_IMGREMOVE, {
					data: {
						sessionuid: _uuid,
						idkey: vidkey,
						tagfile: vtagfile
					},
					dataType: 'json', //服务器返回json格式数据
					type: 'post', //HTTP请求类型
					timeout: 10000, //超时时间设置为10秒；
					success: function(data) {
						//console.log(data);

						imgdataToHtml(data.body.allimgs);
					},
					error: function(xhr, type, errorThrown) {
						//异常处理；
						//for (var a in errorThrown)
						//console.log(errorThrown[a]);
					}
				});
			}
			var TMPIMGLIST;

			function backupimg() {
				TMPIMGLIST = _db.getImgList();
				contrastAllImgInfo(TMPIMGLIST, 'up');
			}
			//上传 method：up or down
			function contrastAllImgInfo(vlist, vmethod) {
				mui.ajax(URL_IMGCONTRAST, {
					data: {
						sessionuid: _uuid,
						glist: JSON.stringify(vlist),
						method: vmethod
					},
					dataType: 'json', //服务器返回json格式数据
					type: 'post', //HTTP请求类型
					timeout: 100000, //超时时间设置为10秒；
					success: function(data) {
						console.log("begin");
						if(vmethod == 'up')
							uploadallimgs(data);
					},
					error: function(xhr, type, errorThrown) {
						console.log("serr")
						//异常处理；
						//for (var a in errorThrown)
						//console.log(errorThrown[a]);
					}
				});
			}

			function uploadallimgs(data) {
				for(var i = 0; i < data.length; i++) {
					var a = data[i];
					console.log(a);
					createImgUpload(a, true);
				}
			}

			function createImgUpload(filepath, key) {
				var w;
				if(key) {
					//提示上传进度
				}
				var file = _fi.analyseUrl(IMGSAVEPATH + filepath);
				//console.log(file["fullpath"]);
				var task = plus.uploader.createUpload(URL_IMGUPLOAD, {
					method: "POST"
				}, function(upload, status) {
					if(upload.state == 4 && status == 200) {

						var msg = JSON.parse(upload.responseText)
						//imgdataToHtml(msg.body.allimgs);
						console.log("上传成功！" + msg.body.allimgs);
						console.log("上传成功！" + filepath);
						queryimglist()
					}
				});
				task.addData("sessionuid", _uuid);
				task.addFile(file["fullpath"], {
					key: "file"
				});
				//key=file 不能随便改，后台用来识别文件key值用，上传多个文件时key值不同

				// 设置自定义数据头
				//Content-Type:application/x-www-form-urlencoded 
				//task.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

				task.addEventListener("statechanged", onUploadStateChanged, false);
				task.start();
			}

			function onUploadStateChanged(upload, status) {
				var process = upload.uploadedSize / upload.totalSize + '%';
			}

			function downloadallimgs(data) {
				for(var i = 0; i < data.length; i++) {
					var a = data[i];
					createImgDownload(a.srcfile, false);
				}
			}

			function createImgDownload(vfilename, key) {
				var w;
				if(key) {
					w = plus.nativeUI.showWaiting("　　 开始下载...　　");
				}
				var filepath = IMGSAVEPATH + vfilename; //???
				_fi.deleteFileByURL(filepath);
				//console.log(vfileid);
				var options = {
					method: "POST",
					data: {
						sessionuid: _uuid,
						srcfile: vfilename
					},
					filename: filepath
				};
				dtask = plus.downloader.createDownload(URL_IMGDOWNLOAD, options,
					function(d, status) {
						if(status == 200) {
							//console.log("下载成功：" + d.filename);
							mui.toast("下载成功 ！使用流量：" + (d.totalSize / 1024).toFixed(3) + 'K');

							G(vfilename).src = REALIMGPATH + vfilename;
						} else {

							//mui.toast("下载失败");
							//w.close();
							if(key) {
								plus.nativeUI.alert("下载更新资源失败！");
							}
						}
					});
				if(key) {
					dtask.addEventListener("statechanged", function(download, status) {

						switch(download.state) {
							case 1: // 开始
								w.setTitle("　　 开始下载...　　 ");
								break;
							case 2: // 已连接到服务器
								w.setTitle("　　 开始下载...　　 ");
								break;
							case 3:
								var a = download.downloadedSize / download.totalSize * 100;
								w.setTitle("　　 已下载" + parseInt(a) + "%　　 ");
								break;
							case 4: // 下载完成
								//console.log("download.totalSize "+download.totalSize )
								w.close();
								break;
						}

					}, false);
				}

				dtask.start();
			}
		</script>
	</body>

</html>